//
//  STTipsBackVC.m
//  ShaBaoOnline
//
//  Created by xujing on 16/8/22.
//  Copyright © 2016年 com.ShaBaoOnline.www. All rights reserved.
//

#import "STTipsBackVC.h"
#import <AVFoundation/AVCaptureDevice.h>
#import <AVFoundation/AVMediaFormat.h>
#import "HHAlertView.h"
#import "STNetworkRequest.h"

#define KBUT_CANMODIFY_COLOR [UIColor colorWithRed:23.0f/255 green:108.0f/255 blue:237.0f/255 alpha:0.83f]

@interface STTipsBackVC ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,UITextViewDelegate,HHAlertViewDelegate>
@property (strong, nonatomic) IBOutlet UITextView *tipTextView;
@property (strong, nonatomic) IBOutlet UIButton *TipImgOne;
@property (strong, nonatomic) IBOutlet UIButton *TipImgTwo;
@property (strong, nonatomic) IBOutlet UIButton *TipImgThree;
@property (nonatomic ,strong)NSString *Tipspicture1;//picture1
@property (nonatomic ,strong)NSString *Tipspicture2;//picture2
@property (nonatomic ,strong)NSString *Tipspicture3;//picture3
@property (nonatomic ,assign)NSInteger buttonId;
@property (nonatomic ,strong)NSString *textViewStr;
@property (nonatomic, strong, nullable) HHAlertView *alertview;
@property (weak, nonatomic) IBOutlet UIView *tipView;
@end

@implementation STTipsBackVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNavigationItem];
    self.tipTextView.delegate = self;
    [self setupPleaseholde];
    
    self.tipView.borderWidth = 1;
    self.tipView.borderColor = [UIColor colorWithRed:217/255.0 green:217/255.0 blue:217/255.0 alpha:1];
}
//设置导航控制器
-(void)setNavigationItem{
    self.navigationItem.title = @"反馈意见";
    UIBarButtonItem *leftBackButton = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"fanghui"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:self action:@selector(goToBack)];
    self.navigationItem.leftBarButtonItem = leftBackButton;
}
//提示语;
- (void)setupPleaseholde {
   NSString * pleaeseStr = @"请简要描述你的问题和意见";
   self.tipTextView.text = pleaeseStr ;
    self.tipTextView.textColor = [UIColor colorWithRed:255/256 green:0 blue:0 alpha:0.3];
    self.textViewStr = @"";
}
//返回
-(void)goToBack{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)textViewDidBeginEditing:(UITextView *)textView {
    textView.text = self.textViewStr;
}
#pragma mark -----------------------------------------textViewDelegate
- (void)textViewDidChange:(UITextView *)textView {
     textView.textColor = [UIColor blackColor];
}
- (void)textViewDidEndEditing:(UITextView *)textView {
     NSString *textStr = textView.text;
    self.textViewStr = textView.text;
    if (textStr.length == 0) {
        [self setupPleaseholde];
             }  
}
//上传信息;
- (IBAction)senderTipsAndImageToback:(id)sender {
//
//    [self.view  endEditing:YES];
//    NSString *tipStr = @"";
//    tipStr = [self.textViewStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
//    NSMutableArray *pictureArray = [NSMutableArray array];
//    NSMutableDictionary *requestParameter = [NSMutableDictionary dictionary];
//
//        if (self.Tipspicture1.length  != 0) {
//            [pictureArray addObject:self.Tipspicture1];
//            
//        }
//        if (self.Tipspicture2.length != 0) {
//            [pictureArray addObject:self.Tipspicture2];
//            
//        }
//        if (self.Tipspicture3.length != 0) {
////            requestParameter[@"certid_back_url"] = @(pictureArray.count);
//            [pictureArray addObject:self.Tipspicture3];
//            
//        }
//
//    
//    requestParameter[@"salerId"] = loginSalerInfo.ID;//@"10000521";
//    requestParameter[@"token"]  = token;
//    requestParameter[@"content"]  = tipStr;
//    if (tipStr != nil && tipStr.length == 0) {
//        [MBProgressHUD showError:@"请输入您的意见和问题"];
//        return;
//    }
//    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//    if (pictureArray.count != 0) {
//        [[STNetworkRequest shareRequest] startPostUpload:api_addFeedbackPhoto params:requestParameter iconFile:nil imageFiles:pictureArray onCompletion:^(id jsonResponse) {
//            [MBProgressHUD hideHUDForView:self.view animated:YES];
//            int result = [[jsonResponse objectForKey:@"result"] intValue];
//            if (1 == result) {
//                //修改资料成功
//                //[self setUpAlertView];
//                
//                [self goSuccess];
//            }else {
//                [MBProgressHUD showError:@"反馈意见失败"];
//            }
//
//        } onError:^(id jsonResponse) {
//            [MBProgressHUD hideHUDForView:self.view animated:YES];
//            [MBProgressHUD showError:@"暂无网络"];
//        }];
//    }else{
//        
//        [[STNetworkRequest shareRequest]startPostUpload:api_addFeedback params:requestParameter onCompletion:^(id jsonResponse) {
//            [MBProgressHUD hideHUDForView:self.view animated:YES];
//            int result = [[jsonResponse objectForKey:@"result"] intValue];
//            if (1 == result) {
////           [self setUpAlertView];
//                 [self goSuccess];
//            }else {
//                [MBProgressHUD showError:@"反馈意见失败"];
//            }
//        } onError:^(id jsonResponse) {
//            [MBProgressHUD hideHUDForView:self.view animated:YES];
//            [MBProgressHUD showError:@"暂无网络"];
//        }];
//    }
}

- (void)goSuccess {
    [MBProgressHUD showSuccess:@"反馈意见成功"];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
         [self.navigationController popViewControllerAnimated:YES];
        
    });
   
}




- (void)setUpAlertView {

    NSString *detils = @"您的反馈已经提交,我们将\n3个工作日内给您答复\n谢谢!";
    // self.alertview.isLogo = NO;
    self.alertview = [[HHAlertView alloc] initWithTitle:nil detailText:detils cancelButtonTitle:@"确定" otherButtonTitles:nil type:YES];
    
    _alertview.mode = HHAlertViewModeNOView;
    _alertview.cancelButton.backgroundColor = KBUT_CANMODIFY_COLOR ;
     [_alertview setCustomView:[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"success"]]];
    _alertview.delegate = self;
    [_alertview show];



}
//选择图片1
- (IBAction)selectImgOneButAction:(id)sender {
    _buttonId = 1;
    [self.view endEditing:YES];
    [self popAleractionView];
}

//选择图片2
- (IBAction)selectImgTwoButAction:(id)sender {
    _buttonId = 2;
     [self.view endEditing:YES];
      [self popAleractionView];
}

//选择图片3
- (IBAction)selectImgThreeButAction:(id)sender {
    _buttonId = 3;
     [self.view endEditing:YES];
      [self popAleractionView];
}

#pragma mark Showphoto
-(void)popAleractionView{
    UIAlertController *actionController = [UIAlertController alertControllerWithTitle:@"选择" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    __weak typeof(self) navc = self;
    UIAlertAction *actionCamera = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        //判断用户是否有权限访问拍照
        AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        
        if (status == AVAuthorizationStatusRestricted || status == AVAuthorizationStatusDenied) {
            
            [MBProgressHUD showError:@"无法打开相机,请在隐私设置中打开权限"];
            return;
        }
        
        UIImagePickerController *pc = [[UIImagePickerController alloc]init];
        pc.sourceType = UIImagePickerControllerCameraCaptureModeVideo;
        pc.delegate = navc;
        pc.navigationBar.backgroundColor = [UIColor blueColor];
        [self.navigationController presentViewController:pc animated:YES completion:nil];
    }];
    UIAlertAction *actionPhoto =[UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UIImagePickerController *pc = [[UIImagePickerController alloc]init];
        pc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        pc.delegate = navc;
        pc.navigationBar.backgroundColor = [UIColor blueColor];
        [self.navigationController presentViewController:pc animated:YES completion:nil];
        
    }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [actionController addAction:actionCamera];
    [actionController addAction:actionPhoto];
    [actionController addAction:cancel];
    [self.navigationController presentViewController:actionController animated:YES completion:nil];
}
#pragma mark UIImagePickerControllerDelegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    if (1 == _buttonId) {
        [self.TipImgOne setImage:info[UIImagePickerControllerOriginalImage] forState:UIControlStateNormal];
        NSString *fileName = [NSString stringWithFormat:@"businessLicenseUrl"];
        _Tipspicture1 = [self saveImage:info[UIImagePickerControllerOriginalImage] WithName:fileName];
    }else if (2 == _buttonId){
        [self.TipImgTwo setImage:info[UIImagePickerControllerOriginalImage] forState:UIControlStateNormal];
        NSString *fileName = [NSString stringWithFormat:@"legalManFrontUrl"];
       _Tipspicture2 = [self saveImage:info[UIImagePickerControllerOriginalImage] WithName:fileName];
    }else{
        [self.TipImgThree setImage:info[UIImagePickerControllerOriginalImage] forState:UIControlStateNormal];
        NSString *fileName = [NSString stringWithFormat:@"legalManBackUrl"];
        _Tipspicture3 = [self saveImage:info[UIImagePickerControllerOriginalImage] WithName:fileName];
    }
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark save file as document
- (NSString *)saveImage:(UIImage *)tempImage WithName:(NSString *)imageName
{
    NSData* imageData = nil;
    
    //    if (UIImagePNGRepresentation(tempImage) == nil)
    //    {
    imageName = [imageName stringByAppendingString:@".jpg"];
    imageData = UIImageJPEGRepresentation(tempImage, 0.1);
    //    }else{
    //        imageName = [imageName stringByAppendingString:@".png"];
    //        imageData = UIImagePNGRepresentation(tempImage);
    //    }
    
    NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString* documentsDirectory = [paths objectAtIndex:0];
    
    NSString* fullPathToFile = [documentsDirectory stringByAppendingPathComponent:imageName];
    [imageData writeToFile:fullPathToFile atomically:NO];
    
    return fullPathToFile;
}


@end
